/**
 * Created by Janpoem on 2016/1/31 0031.
 */

const db = require('./db');

const Cache = require('./cache');

var callFn = function (fn, obj, args) {
	if (typeof fn === 'function') {
		fn.apply(obj, args || []);
	}
};

var commandCache = new Cache('commandCache', {
	life: 60 * 5, // 命令缓存5分钟
	onload: function(name, fn) {
		var me = this;
		db.query('select * from command where name = ? limit 1', [name], function(error, rows) {
			var data = db.row(rows, 0);
			if (data !== false)
				me.save(name, data);
			Cache.call(fn, me, [name, data, true]);
		});
	},
	onloadId: function(id, fn) {
		var me = this;
		db.query('select * from command where id = ? limit 1', [id], function(error, rows) {
			var data = db.row(rows, 0);
			if (data !== false)
				me.save(id, data);
			Cache.call(fn, me, [id, data, true]);
		});
	}
});

commandCache.loadId = function(name, fn) {
	if (name === '' || name === false || name === 'null' || typeof name === 'undefined') {
		console.log('cache ' + name + ' invalid key');
		callFn(fn, this, [name, false]);
	}
	else {
		if (this.data[name] && this.data[name] !== false) {
			var expire = new Date(this.data[name].update.getTime());
			expire.setSeconds(expire.getSeconds() + this.options.life);
			var now = new Date();
			if (now.getTime() < expire.getTime()) {
				console.log('cache ' + name + ' hit, life ' + parseInt((expire.getTime() - now.getTime()) / 1000) + ' second');
				callFn(fn, this, [name, this.data[name].data]);
				return this;
			}
		}
		console.log('cache ' + name + ' load');
		callFn(this.options.onloadId, this, [name, fn]);
	}
	return this;
};

module.exports = commandCache;